﻿/*****************************************************************
 *@Copyright all rights reserved © 2014 Yuga
 *@author Oplink OMS
 *Contact: zengkang007@gmail.com
 *****************************************************************/
package com.oplink.webems.modules.sys.service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.ImmutableList;
import com.oplink.webems.common.persistence.Page;
import com.oplink.webems.common.utils.UserUtils;
import com.oplink.webems.modules.sys.dao.MenuDao;
import com.oplink.webems.modules.sys.entity.Menu;

/**
 * 告警Service
 * 
 * @author Oplink OMS
 * @version 2014-09-02
 */
@Component
@Transactional
public class MenuService {

	private static Logger logger = LoggerFactory.getLogger(MenuService.class);

	@Autowired
	private MenuDao menuDao;

	public Menu get(Long id) {
		return menuDao.findOne(id);
	}

	public List<Menu> findAll() {
		return menuDao.findAll();
	}

	public Page<Menu> find(Page<Menu> page, Menu sysMenu) {
		DetachedCriteria dc = menuDao.createDetachedCriteria();
		// 添加查询条件
		dc.add(Restrictions.eq(Menu.DEL_FLAG, Menu.DEL_FLAG_NORMAL));
		dc.addOrder(Order.asc("parentIds"));
		return menuDao.find(page, dc);
	}

	/**
	 * @function 创建查询
	 **/
	public Page<Menu> getUserSysMenu(Page<Menu> page, Menu sysMenu) {
		DetachedCriteria dc = menuDao.createDetachedCriteria();
		// 添加查询条件
		dc.add(Restrictions.eq(Menu.DEL_FLAG, Menu.DEL_FLAG_NORMAL));
		dc.addOrder(Order.asc("id"));
		return menuDao.find(page, dc);
	}

	public Menu getSysMenu(Long id) {
		return menuDao.findOne(id);
	}

	public void saveSysMenu(Menu entity) {
		menuDao.save(entity);
	}

	public void deleteSysMenu(Long id) {
		menuDao.delete(id);
	}

	@Autowired
	public void setSysMenuDao(MenuDao menuDao) {
		this.menuDao = menuDao;
	}

	public String generateMenuDom(List<Menu> listMenu, String path) {

		StringBuffer html = new StringBuffer("");
		Collections.sort(listMenu, new Comparator<Menu>() {
			@Override
			public int compare(Menu o1, Menu o2) {
				return o1.getParentIds().compareTo(o2.getParentIds());
			}
		});

		// 先放入map
		Map<String, Menu> map = new TreeMap<String, Menu>(new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});

		for (Menu m : listMenu) {
			String id = m.getParentIds();
			map.put(id, m);
		}

		// 然后将map中填入孩子节点
		for (Menu m : listMenu) {
			String id = m.getParentIds();
			String[] idArray = id.split("\\.");
			String last = idArray[idArray.length - 1];
			String parentId = id.replace("." + last, "");

			Menu m_temp = map.get(parentId);
			if (m_temp == null) {
				logger.info("error");
			} else {
				if (!id.equals(parentId)) {
					m_temp.children.put(id, m);
				}
			}
		}

		// 只遍历顶级节点，因为其它节点肯定位于顶级节点内部
		for (String key : map.keySet()) {
			if (!key.contains(".")) {
				Menu m = map.get(key);

				// 如果用户的权限包含该菜单的权限，则可以进行操作
				String roles = UserUtils.getCurrentUserRoles();
				if (!userHasMenuPermission(roles, m.getPermission())) {
					continue;
				}

				html.append("<li class=\"dropdown\"><a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\"> "
						+ m.getLabel() + " <b class=\"caret\"></b></a><ul class=\"dropdown-menu\">");
				for (Menu menu : m.children.values()) {
					generateNode(menu, html, path);
				}
				html.append("</ul></li>");
			}
		}
		return html.toString();
	}

	private void generateNode(Menu m, StringBuffer str, String path) {
		// 如果用户的权限包含该菜单的权限，则可以进行操作
		String roles = UserUtils.getCurrentUserRoles();
		if (!userHasMenuPermission(roles, m.getPermission())) {
			return;
		}

		// 查看有权限的子菜单个数
		int childPermissionSize = 0;
		for (Menu menu : m.children.values()) {
			if (userHasMenuPermission(roles, menu.getPermission())) {
				childPermissionSize++;
			}
		}

		if ((m.children.size() != 0) && (childPermissionSize != 0)) {
			str.append(" <li class=\"dropdown-submenu\"><a class=\"menu_item\" url=\"" + m.getUrl() + "\">"
					+ m.getLabel() + "</a><ul class=\"dropdown-menu\">");
		} else {
			str.append(" <li><a mid=\"" + m.getId() + "\" class=\"menu_item\" url=\"" + path + m.getUrl() + "\">"
					+ m.getLabel() + "</a></li> ");
		}

		for (Menu menu : m.children.values()) {
			generateNode(menu, str, path);
		}

		if ((m.children.size() != 0) && (childPermissionSize != 0)) {
			str.append("</ul></li>");
		}
	}

	private boolean userHasMenuPermission(String userRole, String menuRole) {
		List<String> listMenuRole = ImmutableList.copyOf(StringUtils.split(menuRole, ","));
		List<String> listUserRole = ImmutableList.copyOf(StringUtils.split(userRole, ","));
		for (String mr : listMenuRole) {
			for (String ur : listUserRole) {
				if (ur.equals(mr)) {
					return true;
				}
			}
		}
		return false;
	}
}
